{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "21d48319",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import datetime\n",
    "import os\n",
    "import smtplib\n",
    "import email\n",
    "import datetime\n",
    "# 负责构造文本\n",
    "from email.mime.text import MIMEText\n",
    "# 负责构造图片\n",
    "from email.mime.image import MIMEImage\n",
    "# 负责将多个对象集合起来\n",
    "from email.mime.multipart import MIMEMultipart\n",
    "from email.header import Header\n",
    "today = datetime.date.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9464b406",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:/Users/bwm/Desktop/西南证券实习/5指数计算/指数输入/2021-06-18/'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#填写输入和输出文件夹地址\n",
    "filepath_in = 'C:/Users/bwm/Desktop/西南证券实习/5指数计算/指数输入/'+str(today)+'/'#输入文件夹\n",
    "filepath_out = 'C:/Users/bwm/Desktop/西南证券实习/5指数计算/指数输出/'#输出文件夹\n",
    "filepath_in"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2dfcee9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#读取今日输入文件夹内文件名得到list readpath\n",
    "list_txt=[]\n",
    "for root, ds, fs in os.walk(filepath_in):\n",
    "    for f in fs:\n",
    "        list_txt.append(f)\n",
    "#获得输入文件txt文件路径名readpath\n",
    "readpath=[]\n",
    "for i in list_txt:\n",
    "    readpath.append(filepath_in+i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "44c8f86a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['C:/Users/bwm/Desktop/西南证券实习/5指数计算/指数输入/2021-06-18/WI.0001 2021-06-18.txt',\n",
       " 'C:/Users/bwm/Desktop/西南证券实习/5指数计算/指数输入/2021-06-18/WI.0002 2021-06-18.txt']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#查看所得list是否是我们需要的所有txt文件\n",
    "readpath"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4d15389a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2021, 6, 17)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#计算上个交易日日期（并不是读取昨日的日期，而是读取输出文件夹中上个已有文件夹日期）\n",
    "def filepath_last_day():\n",
    "    day = today - datetime.timedelta(days=1)\n",
    "    for i in range(20):\n",
    "        filepath_yes = filepath_out + str(day)\n",
    "        if os.path.exists(filepath_yes):\n",
    "            return day\n",
    "            break\n",
    "        else:\n",
    "            day = day - datetime.timedelta(days=1)\n",
    "yesterday = filepath_last_day()\n",
    "yesterday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "295490e0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['CU2106.SHF', 'AU2106.SHF', 'SC2107.INE', 'M2108.DCE']\n",
      "[0.2 0.3 0.1 0.4]\n",
      "['CU2106.SHF', 'AU2106.SHF', 'SR107.CZC', 'Y2108.DCE']\n",
      "[0.2 0.3 0.1 0.4]\n"
     ]
    }
   ],
   "source": [
    "#读取每个txt文件中的数据（我们计划是每次循环即对每个txt文件完成读入、计算、输出全部过程，由于缺少中间导数据的过程，为了保证代码\n",
    "#能运行，在此并没有把后面过程写入这个循环里）txt文件第一列为代码，第二列为权重，第三列为交易员计算的今日指数\n",
    "for filepath in readpath:\n",
    "    name = []\n",
    "    qz = []\n",
    "    result=[]\n",
    "    with open(filepath) as filehandle:\n",
    "        for line in filehandle:\n",
    "            line_change = line.replace('\\n','')#去除换行符\n",
    "            a, b,d = line_change.split(',')\n",
    "            \n",
    "            if len(b) == 0:\n",
    "                print('权重存在缺失值')\n",
    "                \n",
    "            c = float(b)#转换为浮点型\n",
    "            name.append(a)\n",
    "            qz.append(c)#权重\n",
    "            result.append(d)\n",
    "        weight = np.array(qz)#转化为向量\n",
    "        \n",
    "        print(name)#输出文件中各期货代码\n",
    "        print(weight)#输出文件中各期货权重\n",
    "        index_result=result[0]#交易员给出的指数\n",
    "        #报错函数\n",
    "        if len(name)!=len(qz):\n",
    "            print('数据长度不等')\n",
    "        if u'' in name:\n",
    "            print('代码存在缺失值')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3533a6fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "#此处从wind导入数据\n",
    "#读取每个证券收益率向量记为return，读取国债收益率r，即输入为一个代码list，输出为每个代码对应收益率，和当日国债收益率\n",
    "#假如得到一个future_return和利率r\n",
    "future_return = [0.01, -0.02, 0.03,0.04]\n",
    "r=0.02"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "231fc27e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#杠杆借钱利息\n",
    "sum_total = weight.sum()#权重和\n",
    "if sum_total > 1:\n",
    "    interest = (sum_total-1)*r/365\n",
    "else:\n",
    "    interest = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "037e3951",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.015"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#在已知每个证券return的情况下求出当日收益率\n",
    "return_today = weight.dot(future_return) - interest#权重向量与收益率向量内积再减去利息\n",
    "return_today"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "762b75e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#计算今日指数点\n",
    "#读取上个交易日excel名\n",
    "file_path, fullname = os.path.split(filepath)\n",
    "fname,ext = os.path.splitext(fullname)\n",
    "fname_yesterday = fname.replace(str(today),str(yesterday))\n",
    "#读取上个交易日excel\n",
    "df_yesterday = pd.read_excel(filepath_out+str(yesterday)+'/'+fname_yesterday+'.xlsx')\n",
    "#读取上个交易日指数\n",
    "zs_yes = df_yesterday['今日指数'].dropna()\n",
    "zs_yesterday = float(zs_yes)\n",
    "#今日指数\n",
    "jr = zs_yesterday*(1+return_today)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0ad96e2d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前计算指数不正确，请检查\n"
     ]
    }
   ],
   "source": [
    "#该模块检查我们算出的指数与交易员给出的指数是否相等\n",
    "if jr != index_result:\n",
    "    print('当前计算指数不正确，请检查')\n",
    "    result_right ='指数错误'\n",
    "else:\n",
    "    print('指数计算正确')\n",
    "    result_right = '指数正确'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8661c304",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "新建文件夹\n"
     ]
    }
   ],
   "source": [
    "#该模块建立今日输出文件夹（如果已建立，则输出已有该文件夹）\n",
    "def mkdir(path):\n",
    "    folder = os.path.exists(path)\n",
    "    if not folder:#新建文件夹\n",
    "        os.makedirs(path)\n",
    "        print(\"新建文件夹\")\n",
    "    else:#已有该文件夹\n",
    "        print(\"已有该文件夹\")\n",
    "filepath_out_today = filepath_out+str(today)#今日输出文件价的文件名\n",
    "#建立今日输出文件夹\n",
    "mkdir(filepath_out_today)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2312bdea",
   "metadata": {},
   "outputs": [],
   "source": [
    "#输出今日excel\n",
    "df1=pd.DataFrame(name,columns=['股票代码'])\n",
    "df2=pd.DataFrame(qz,columns=['成分股权重'])\n",
    "df3=pd.DataFrame(future_return,columns=['收益率(%)'])\n",
    "df4=pd.DataFrame([jr],columns=['今日指数'])\n",
    "df = pd.concat( [df1, df2, df3, df4], axis=1 )\n",
    "file_path, fullname = os.path.split(filepath)\n",
    "fname,ext = os.path.splitext(fullname)\n",
    "file_name =filepath_out+str(today)+'/'+fname+'.xlsx'#输出文件名\n",
    "df.to_excel(file_name, index=False)#输出今日excel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a22cac52",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "send: 'ehlo [192.168.137.1]\\r\\n'\n",
      "reply: b'250-newxmesmtplogicsvrszc7.qq.com\\r\\n'\n",
      "reply: b'250-PIPELINING\\r\\n'\n",
      "reply: b'250-SIZE 73400320\\r\\n'\n",
      "reply: b'250-STARTTLS\\r\\n'\n",
      "reply: b'250-AUTH LOGIN PLAIN XOAUTH XOAUTH2\\r\\n'\n",
      "reply: b'250-AUTH=LOGIN\\r\\n'\n",
      "reply: b'250-MAILCOMPRESS\\r\\n'\n",
      "reply: b'250 8BITMIME\\r\\n'\n",
      "reply: retcode (250); Msg: b'newxmesmtplogicsvrszc7.qq.com\\nPIPELINING\\nSIZE 73400320\\nSTARTTLS\\nAUTH LOGIN PLAIN XOAUTH XOAUTH2\\nAUTH=LOGIN\\nMAILCOMPRESS\\n8BITMIME'\n",
      "send: 'AUTH PLAIN ADExNzE5MjM2MzZAcXEuY29tAGp6dGlzeHFucnpxeWJhYWI=\\r\\n'\n",
      "reply: b'235 Authentication successful\\r\\n'\n",
      "reply: retcode (235); Msg: b'Authentication successful'\n",
      "send: 'mail FROM:<1171923636@qq.com> size=7782\\r\\n'\n",
      "reply: b'250 OK.\\r\\n'\n",
      "reply: retcode (250); Msg: b'OK.'\n",
      "send: 'rcpt TO:<892744160@qq.com>\\r\\n'\n",
      "reply: b'250 OK\\r\\n'\n",
      "reply: retcode (250); Msg: b'OK'\n",
      "send: 'data\\r\\n'\n",
      "reply: b'354 End data with <CR><LF>.<CR><LF>.\\r\\n'\n",
      "reply: retcode (354); Msg: b'End data with <CR><LF>.<CR><LF>.'\n",
      "data: (354, b'End data with <CR><LF>.<CR><LF>.')\n",
      "send: b'Content-Type: multipart/related; boundary=\"===============4250963907505907336==\"\\r\\nMIME-Version: 1.0\\r\\nFrom: =?utf-8?b?6KW/5Y2X6K+B5Yi45Zy65aSW5Lia5Yqh6YOoPDExNzE5MjM2MzZAcXEuY29tPg==?=\\r\\nTo: =?utf-8?b?5YiY54G15Z2HPDg5Mjc0NDE2MEBxcS5jb20+?=\\r\\nSubject: =?utf-8?b?5LuK5pel5oyH5pWw5paH5Lu2?=\\r\\n\\r\\n--===============4250963907505907336==\\r\\nContent-Type: text/plain; charset=\"utf-8\"\\r\\nMIME-Version: 1.0\\r\\nContent-Transfer-Encoding: base64\\r\\n\\r\\n5L2g5aW977yM6L+Z5piv5LiA5Liq5rWL6K+V6YKu5Lu277yB\\r\\n\\r\\n--===============4250963907505907336==\\r\\nContent-Type: text/base64; charset=\"utf-8\"\\r\\nMIME-Version: 1.0\\r\\nContent-Transfer-Encoding: base64\\r\\nContent-Type: application/octet-stream\\r\\nContent-Disposition: attachment; filename=WI.0002 2021-06-15.xlsx\\r\\n\\r\\nUEsDBBQAAAAIACN9z1IHQU1igQAAALEAAAAQAAAAZG9jUHJvcHMvYXBwLnhtbE2OPQsCMRBE/8px\\r\\nvbdBwUJiQNBSsLIPexsvkGRDskJ+vjnBj24ebxhG3wpnKuKpDi2GVI/jIpIPABUXirZOXaduHJdo\\r\\npWN5ADvnkc6Mz0hJYKvUHqgJpZnmTf4Ojkafcg4erXhO5uqxcGUnw6UhBQ3/cm3eqdQ17yb1lh/W\\r\\n8DtpXlBLAwQUAAAACAAjfc9SLrpl6+sAAADLAQAAEQAAAGRvY1Byb3BzL2NvcmUueG1spZFNT8Mw\\r\\nDIb/ypR767RjmxR1uYA4gYTEJBC3KPG2iOZDiVG7f09btg4EN47x+/ixrTQ6Ch0SPqUQMZHFvOhd\\r\\n67PQccuORFEAZH1Ep3I5EH4I9yE5RcMzHSAq/a4OCDXna3BIyihSMAqLOBvZWWn0rIwfqZ0ERgO2\\r\\n6NBThqqs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y54\\r\\nbWxQSwECFAAUAAAACAAjfc9St0frisAAAAAWAgAACwAAAAAAAAAAAAAAgAE5DQAAX3JlbHMvLnJl\\r\\nbHNQSwECFAAUAAAACAAjfc9S9nUBqjABAAApAgAADwAAAAAAAAAAAAAAgAEiDgAAeGwvd29ya2Jv\\r\\nb2sueG1sUEsBAhQAFAAAAAgAI33PUjPr47qtAAAA+wEAABoAAAAAAAAAAAAAAIABfw8AAHhsL19y\\r\\nZWxzL3dvcmtib29rLnhtbC5yZWxzUEsBAhQAFAAAAAgAI33PUpuGQoQbAQAA1wMAABMAAAAAAAAA\\r\\nAAAAAIABZBAAAFtDb250ZW50X1R5cGVzXS54bWxQSwUGAAAAAAkACQA+AgAAsBEAAAAA\\r\\n\\r\\n--===============4250963907505907336==--\\r\\n.\\r\\n'\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "邮件发送成功\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "reply: b'250 OK: queued as.\\r\\n'\n",
      "reply: retcode (250); Msg: b'OK: queued as.'\n",
      "data: (250, b'OK: queued as.')\n",
      "send: 'quit\\r\\n'\n",
      "reply: b'221 Bye.\\r\\n'\n",
      "reply: retcode (221); Msg: b'Bye.'\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(221, b'Bye.')"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#自动发邮件\n",
    "# SMTP服务器,这里使用163邮箱\n",
    "mail_host = \"smtp.qq.com\"\n",
    "# 发件人邮箱\n",
    "mail_sender = \"1171923636@qq.com\"\n",
    "# 邮箱授权码,注意这里不是邮箱密码\n",
    "mail_license = \"XXXXXXXXXXXXX\"\n",
    "# 收件人邮箱，可以为多个收件人\n",
    "mail_receivers = [\"892744160@qq.com\"]\n",
    "mm = MIMEMultipart('related')\n",
    "# 邮件主题\n",
    "subject_content = \"\"\"今日指数文件\"\"\"\n",
    "# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱\n",
    "mm[\"From\"] = '西南证券场外业务部<1171923636@qq.com>'\n",
    "# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱\n",
    "mm[\"To\"] = '刘灵均<892744160@qq.com>'\n",
    "# 设置邮件主题\n",
    "mm[\"Subject\"] = Header(subject_content,'utf-8')\n",
    "# 邮件正文内容\n",
    "body_content = \"\"\"你好，这是一个测试邮件！\"\"\"\n",
    "# 构造文本,参数1：正文内容，参数2：文本格式，参数3：编码方式\n",
    "message_text = MIMEText(body_content,\"plain\",\"utf-8\")\n",
    "# 向MIMEMultipart对象中添加文本对象\n",
    "mm.attach(message_text)\n",
    "# 构造附件\n",
    "attachment = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8')#此处选择要发送的excel文件，修改file_name\n",
    "# 设置附件信息\n",
    "attachment[\"Content-Type\"] = 'application/octet-stream'\n",
    "basename = fname+'.xlsx'\n",
    "attachment[\"Content-Disposition\"] = 'attachment; filename='+str(basename)\n",
    "# 添加附件到邮件信息当中去\n",
    "mm.attach(attachment)\n",
    "# 创建SMTP对象\n",
    "stp = smtplib.SMTP()\n",
    "# 设置发件人邮箱的域名和端口，端口地址为25\n",
    "stp.connect(mail_host, 25)  \n",
    "# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息\n",
    "stp.set_debuglevel(1)\n",
    "# 登录邮箱，传递参数1：邮箱地址，参数2：邮箱授权码\n",
    "stp.login(mail_sender,mail_license)\n",
    "# 发送邮件，传递参数1：发件人邮箱地址，参数2：收件人邮箱地址，参数3：把邮件内容格式改为str\n",
    "stp.sendmail(mail_sender, mail_receivers, mm.as_string())\n",
    "print(\"邮件发送成功\")\n",
    "# 关闭SMTP对象\n",
    "stp.quit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f37e083",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
